package org.caijin.springzookeeper.Id;

import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SnowflakeIdTest {
    public static void main(String[] args) throws InterruptedException {
        long workerID = SnowflakeIdWorker.instance.getId();
        SnowflakeIdGenerator.instance.init(workerID);
        ExecutorService threadPool = Executors.newSingleThreadExecutor();

        final HashSet idSet = new HashSet();
        Collections.synchronizedCollection(idSet);
        Long startTime = System.currentTimeMillis();
        log.info("start generate id *");
        int threadCount = 10;
        int turn = 50000;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            threadPool.execute(()->{
                for (long j = 0; j < turn; j++) {
                    long id = SnowflakeIdGenerator.instance.nextId();
                    synchronized (idSet) {
//                        if (j%10000==0){
//                            log.info("线程{}生成第{}个 id 为:{}",Thread.currentThread().getName(),j,id);
//                        }
                        log.info("线程{}生成第{}个 id 为:{}",Thread.currentThread().getName(),j,id);
                        idSet.add(id);
                        System.out.println(idSet.size());
                    }
                }
                countDownLatch.countDown();
        });
        countDownLatch.await(50000 , TimeUnit.MICROSECONDS);
        threadPool.shutdown();
        threadPool.awaitTermination(10 , TimeUnit.SECONDS);
        long endTime = System.currentTimeMillis();
        log.info("end generate id ");
        log.info("* cost "+ (endTime - startTime) + " ms!");

        };

}
}
